package com.eastdigit.system.controller;

import com.eastdigit.servlet.ReqBean;
import com.eastdigit.servlet.RequestAttribute;
import com.eastdigit.servlet.Response;
import com.eastdigit.system.model.Menu;
import com.eastdigit.system.service.IMenuService;
import net.sf.json.JSONObject;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/menu")
public class MenuController {

    @Autowired
    private IMenuService menuService;

    @RequestMapping(value = "/treeGrid")
    @ResponseBody
    public JSONObject queryMenuGrid(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        return Response.response(menuService.queryMenuTreeGrid(reqBean.getUserId()));
    }

    @RequestMapping(value = "/tree")
    @ResponseBody
    public JSONObject queryMenu(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        return Response.response(menuService.queryMenuTree(reqBean.getUserId()));
    }

    @RequestMapping(value = "/add")
    @ResponseBody
    public JSONObject addMenu(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        menuService.add(getMenu(reqBean));
        return Response.responseSuccess();
    }

    @RequestMapping(value = "/update")
    @ResponseBody
    public JSONObject updateMenu(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        menuService.update(getMenu(reqBean));
        return Response.responseSuccess();
    }

    @RequestMapping(value = "/delete")
    @ResponseBody
    public JSONObject removeMenu(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        menuService.delete(reqBean.getInfo("menuId"));
        return Response.responseSuccess();
    }

    /**
     * 从表单获取对象
     * 
     * @param reqBean
     * @return
     */
    private Menu getMenu(ReqBean reqBean) {
        Menu menu = new Menu();
        menu.setId(reqBean.getInfo("menuId"));
        menu.setParentId(NumberUtils.toInt(reqBean.getInfo("parentMenuId"), 0) + "");
        menu.setName(reqBean.getInfo("menuName"));
        menu.setIcon(reqBean.getInfo("icon"));
        menu.setUrl(reqBean.getInfo("menuUrl"));
        menu.setCtrlName(reqBean.getInfo("ctrlName"));
        menu.setCtrlPath(reqBean.getInfo("ctrlPath"));
        menu.setTemplateUrl(reqBean.getInfo("templateUrl"));
        menu.setOrder(reqBean.getInfoInt("menuOrder"));
        menu.setType(reqBean.getInfo("menuType"));
        menu.setState(reqBean.getInfo("menuState"));
        menu.setOperator(reqBean.getUserId());
        menu.setRemark(reqBean.getInfo("remark"));
        menu.setExtra1(reqBean.getInfo("extra1"));
        return menu;
    }
}
